﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Mail;
using System.Text;
using System.Data.Entity;
using System.Threading;
using System.Timers;
using Wicresoft.TFSAutoNotify.Common;

namespace Wicresoft.TFSAutoNotify.Email
{
    class Program
    {
        static Tfs_AutoNotifyEntities tfsDB = new Tfs_AutoNotifyEntities();
        static void Main(string[] args)
        {
            LogRunInfo.Ready();
            System.Timers.Timer timesDo = new System.Timers.Timer(5  * 1000);
            timesDo.Interval = 5 *1000;

            timesDo.Elapsed += new System.Timers.ElapsedEventHandler(OnTimedEvent);
            timesDo.AutoReset = true;
            timesDo.Enabled = true;

            timesDo.Start();
            GC.KeepAlive(timesDo);
            while (true)
            {
                Console.Read();
            }
            // When autoEvent si
        }
        private static void OnTimedEvent(object source, ElapsedEventArgs e)
        {
            Console.WriteLine("The Email event was raised at {0}", e.SignalTime);
            CheckShelve();
        }
        public static void CheckShelve()
        {
            var y = GetNotSentList();

            if (y != null)
            {
                foreach (var x in y)
                {
                    SendEmail(x);
                    x.IsSent = true;
                    x.SentTime = DateTime.Now;
                    tfsDB.SaveChanges();
                }
            }

        }
        public static ShelveInfo[] GetNotSentList()
        {
            var noSent = tfsDB.ShelveInfos.Where(p => p.IsSent == false);
            return noSent.ToArray();
        }
        public static void SendEmail(ShelveInfo _shelveInfo)
        {

            string to = _shelveInfo.MailTo;
            string from = _shelveInfo.MailFrom;
            MailMessage message = new MailMessage(from, to);
            message.Subject = _shelveInfo.Subject;
            message.IsBodyHtml = true;
            message.Body = _shelveInfo.Body;
            message.Priority = MailPriority.Normal;
            EmployeesInfo _Es = tfsDB.EmployeesInfos.First(p => _shelveInfo.Owner.Contains(p.Ad4Account));
            message.ReplyToList.Add(new MailAddress(_Es.Email, _Es.EnglishName));
            char[] _char = new char[10];
            _char[0] = ';';
            foreach (var x in SeparateStr(_shelveInfo.CC, _char))
            {
                if (x != null && x.Contains("@"))
                {
                    message.CC.Add(x);
                }
            }
            foreach (var x in SeparateStr(_shelveInfo.BCC, _char))
            {
                if (x != null && x.Contains("@"))
                {
                    message.Bcc.Add(x);
                }
            }
            SmtpClient client = new SmtpClient("172.24.146.133", 25);
            // Credentials are necessary if the server requires the client 
            // to authenticate before it will send e-mail on the client's behalf.
            //client.Credentials = CredentialCache.DefaultNetworkCredentials;
            try
            {
                client.Send(message);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Exception caught in CreateTestMessage1(): {0}",
                      ex.ToString());
            }
            finally
            {
                string x = "Send TO " + _Es.EnglishName + " Successful " + "   Subject Is  " + message.Subject;
                Console.WriteLine(x);
                LogRunInfo.Write(x);
            }
        }
        public static List<string> SeparateStr(string str, char[] sepChar)
        {
            List<string> strList = new List<string>();
            if (str == null)
            {
                strList = null;
            }
            else
            {
                string[] _x = str.Split(sepChar);

                foreach (var _y in _x)
                {
                    if (_y != null)
                    {
                        strList.Add(_y);
                    }
                }
            }

            return strList;
        }
    }
}
